// dParserGenerator.cpp : Defines the entry point for the console application.
//
#include "dParserCompiler.h"

bool CheckDependency(const char* const target, const char* const source)
{
	struct _stat sourceStat;
	struct _stat targetStat;
	int result = _stat (target, &targetStat);
	if( result == 0 ) {
		result = _stat (source, &sourceStat);
		if( result == 0 ) {
			return targetStat.st_mtime > sourceStat.st_mtime;
		}
	}

	return false;
}

#if defined(_DEBUG)
int DebugMemory(int allocType, void *userData, size_t size,
	int blockType, long requestNumber,
	const unsigned char *filename, int lineNumber)
{
	//if (requestNumber == 654427) {
	//	requestNumber *=1;
	//}
	return TRUE;
}
#endif

int main(int argc, char* argv[])
{
	#if defined(_DEBUG) && defined (_MSC_VER)
		_CrtSetDbgFlag( _CRTDBG_LEAK_CHECK_DF | _CRTDBG_ALLOC_MEM_DF);
		//_CrtSetBreakAlloc (634);
		_CrtSetAllocHook(DebugMemory);
	#endif

	if (argc < 4) {
		fprintf (stdout, "usage: dParcelGenerator [GrammarFile] [scannerClasName] [OutputFileName]\n");
		fprintf (stdout, "[GrammarFile] name of the file containing a Yacc like Grammar file\n");
		fprintf (stdout, "[ScannerClass] Name of the Scanner Class Generated by dLexGenerator\n");
		fprintf (stdout, "[OutputFileName] name of the file cpp output file\n");
		exit (0);
	}

	const char* const inputRulesFileName = argv[1];
	const char* const scannerClassName = argv[2];
	const char* const outputFileName = argv[3];

	if (!CheckDependency (outputFileName, inputRulesFileName)) {
		FILE* const rules = fopen (inputRulesFileName, "rb");
		if (!rules) {
			fprintf (stdout, "Rule file \"%s\" not found\n",  inputRulesFileName);
			exit (0);
		}

		time_t mytime = time(NULL);
		char * time_str = ctime(&mytime);
		time_str[strlen(time_str) - 1] = '\0';
		fprintf (stdout, "start time : %s\n", time_str);

		dString buffer;
		buffer.LoadFile(rules);
		fclose (rules);
		dParserCompiler parcel (buffer, outputFileName, scannerClassName);

		mytime = time(NULL);
		time_str = ctime(&mytime);
		time_str[strlen(time_str) - 1] = '\0';
		fprintf (stdout, "finish Time : %s\n", time_str);
	}
	return 0;
}

